<template>
  <div class="h-full">
    <CodeMirrorEditor
      :value="getValue"
      @change="handleValueChange"
      :mode="mode"
      :readonly="readonly"
      :tabSize="tabSize"
      :lineWrapping="lineWrapping"
      :lineNumbers="lineNumbers"
      :border="border"
    />
  </div>
</template>
<script lang="ts" setup>
  import type { PropType } from 'vue';
  import { computed } from 'vue';
  import CodeMirrorEditor from './components/CodeMirror.vue';
  import { isString } from '@/utils/is';
  import { MODE } from './types/index.d';

  const props = defineProps({
    value: { type: [Object, String] as PropType<Record<string, any> | string> },
    mode: {
      type: String as PropType<MODE>,
      default: MODE.JSON,
      validator(value: any) {
        // 这个值必须匹配下列字符串中的一个
        return Object.values(MODE).includes(value);
      },
    },
    readonly: { type: Boolean },
    tabSize: { type: Number, default: 2 },
    lineWrapping: { type: Boolean, default: true },
    lineNumbers: { type: Boolean, default: true },
    border: { type: Boolean, default: true },
    autoFormat: { type: Boolean, default: true },
  });

  const emit = defineEmits(['change', 'update:value', 'format-error']);

  const getValue = computed(() => {
    const { value, mode, autoFormat } = props;
    if (!autoFormat || mode !== MODE.JSON) {
      return value as string;
    }
    let result = value;
    if (isString(value) && mode === MODE.JSON) {
      try {
        result = JSON.parse(value);
      } catch (e) {
        emit('format-error', value);
        return value as string;
      }
      return JSON.stringify(result, null, 2);
    }
    return result as string;
  });

  function handleValueChange(v: any) {
    emit('update:value', v);
    emit('change', v);
  }
</script>
